//index.js
//获取应用实例
import { Data } from './index.data';
var app = getApp()
Page({
  data: Data,
  navigateToClock: function (e) {
    toclock(e)
  },
  onShow: function () {
    var that = this;
    login(that)
  }, 
  onLoad:function(){
   
  },
  onPullDownRefresh: function () {
    var that = this;
    getTodayData(that, wx.getStorageSync('userInfo').patientid, 'pullDown');
  },
  onShareAppMessage: function () {
    return {
      title: '爱丁生活方式管理营',
    }
  },

// 早间
  //点击显示隐藏时间
  tapbreakfast: function (e) {
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
          'timesnew': e_data.times,
        });
     if(that.data.breakfast){
           //表示显示了，需要隐藏
            that.setData({
          'breakfast': false,
        });
        }else{
          //表示隐藏，需要显示
          that.setData({
          'breakfast': true,
        });
        }   
  },
  // 上午
  tapmorning:function(e){
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
      'timesnew': e_data.times,
    });
    if (that.data.morning) {
      //表示显示了，需要隐藏
      that.setData({
        'morning': false,
      });
    } else {
      //表示隐藏，需要显示
      that.setData({
        'morning': true,
      });
    }

  },
  // 午餐
  taplunch: function(e){
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
      'timesnew': e_data.times,
    });
    if (that.data.lunch) {
      //表示显示了，需要隐藏
      that.setData({
        'lunch': false,
      });
    } else {
      //表示隐藏，需要显示
      that.setData({
        'lunch': true,
      });
    }
  },
  // 下午加餐
  tapafternoon: function (e) {
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
      'timesnew': e_data.times,
    });
    if (that.data.afternoon) {
      //表示显示了，需要隐藏
      that.setData({
        'afternoon': false,
      });
    } else {
      //表示隐藏，需要显示
      that.setData({
        'afternoon': true,
      });
    }

  },
// 晚餐
  tapdinner: function (e) {
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
      'timesnew': e_data.times,
    });
    if (that.data.dinner) {
      //表示显示了，需要隐藏
      that.setData({
        'dinner': false,
      });
    } else {
      //表示隐藏，需要显示
      that.setData({
        'dinner': true,
      });
    }

  },
  // 睡前
  tapBeforebed: function (e) {
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
      'timesnew': e_data.times,
    });
    if (that.data.Beforebed) {
      //表示显示了，需要隐藏
      that.setData({
        'Beforebed': false,
      });
    } else {
      //表示隐藏，需要显示
      that.setData({
        'Beforebed': true,
      });
    }

  },
  // 其他
  tapother: function (e) {
    var that = this;
    var e_data = e.currentTarget.dataset;
    that.setData({
      'timesnew': e_data.times,
    });
    if (that.data.other) {
      //表示显示了，需要隐藏
      that.setData({
        'other': false,
      });
    } else {
      //表示隐藏，需要显示
      that.setData({
        'other': true,
      });
    }

  }


})
//查看打卡详情
function toclock(e) {
  var that=this
  console.log(e);
  var e_data = e.currentTarget.dataset;
  console.log(e_data);
  //表示已经打卡
  if (e_data.state == 1) {

    // 体温打卡之后
    if (e_data.type == 7 || e_data.type==11) {
      wx.navigateTo({
        url: '../chartlook/chartlook?dietId=' + e_data.id + '&type=' + e_data.type + "&sign=" + e_data.sign + '&times=' + e_data.times  
      })
    } else if(e_data.type==9){
     // 月经打卡之后
      wx.navigateTo({
        url: '../addcomplete/addcomplete?dietId=' + e_data.id + '&type=' + e_data.type + "&sign=" + e_data.sign + '&times=' + e_data.times  
      })
    } else {
      //其他打卡之后
      wx.navigateTo({
        url: '../clock/clock?id=' + e_data.id + '&type=' + e_data.type + "&sign=" + e_data.sign + '&times=' + e_data.times+ '&patientid=' + wx.getStorageSync('userInfo').patientid
      })
    }
  } else if (e_data.state == 0) {
     //表示未打卡
   
    wx.navigateTo({
      url: '../addclock/addclock?type=' + e_data.type + "&sign=" + e_data.sign + '&times=' + e_data.times
      })
   
  }
}
// 第三方登录
function login(that) {
  var userInfo = wx.getStorageSync('userInfo');
  if (userInfo) {
    console.log('已经登录：' + userInfo);
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      })
    });
    getTodayData(that, wx.getStorageSync('userInfo').patientid);
    getWeekData(that,wx.getStorageSync('userInfo').patientid)
  } else {
    wx.login({
      success: function (res) {
        var code = res.code;
        console.log(code);
        wx.getUserInfo({
          success: function (res) {
            var userinfo = res.userInfo;
            console.log(userinfo)
            app.globalData.userInfo = res.userInfo;
            that.setData({ 'userInfo': userinfo });
            if (userinfo.city==""){
              var params = {
                wxcode: code,
                username: userinfo.nickName,
                icon: userinfo.avatarUrl,
                channel: 'wxmp2'
              };
            }else{
              var params = {
                wxcode: code,
                username: userinfo.nickName,
                icon: userinfo.avatarUrl,
                city: userinfo.city,
                channel: 'wxmp2'
              };
            }
            
            console.log(params)
            app.https.post(that, '/IbabyWebService/3/Patient/wxmpSignUp', params, function (res) {
              wx.setStorageSync('userInfo', res);
              getTodayData(that, res.patientid);
              getWeekData(that,res.patientid)
            })
          },
          fail: function () {
            // fail
            console.log('获取用户信息失败')
          }
        })
      },
      fail: function () {
        console.log('授权失败')
      },
    })
  }
}
//获取今日打卡记录
function getTodayData(that, patientid, pullDown) {
  var params = {
    patientid: patientid
  }
  app.https.get(that, '/IbabyWebService/camp/dietHistoryToday', params, function (res) {

    //每次请求都归0
    that.setData({
      mocount: 0,
      swcount:0,
      wccount:0,
      xccount:0,
      account:0,
      bccount:0,
      occount:0,
      morningcount: '',//早间百分比
      swpercentages: "",//上午百分比
      wcpercentage: '',//午餐百分比
      xccountage: "",//下午百分比
      accountage: "",//晚餐百分比
      bccountage: "",//睡前
      occountage: "",//其他打卡
    })
    var clock = res;
    var clockList = that.data.clockList;
  
    var data = {};
    if (clock.length > 0) {
      var swcount = that.data.swcount;
      for (var i = 0; i < clock.length; i++) { 
         
        if(clock[i].times==1){
          that.data.mocount++;
          that.setData({ mocount: that.data.mocount })
        }
         if (clock[i].times == 2){
          that.data.swcount++;
          that.setData({ swcount: that.data.swcount })
        }
         if (clock[i].times == 3){
          that.data.wccount++;
          that.setData({ wccount: that.data.wccount })
        }
         if (clock[i].times == 4){
          that.data.xccount++  //下午
          that.setData({ xccount: that.data.xccount })
        }
         if (clock[i].times == 5){
          that.data.account++ //晚餐
          that.setData({ account: that.data.account })
        }
         if (clock[i].times == 6){
          that.data.bccount++ //睡前
          that.setData({ bccount: that.data.bccount })
        }
        if (clock[i].times == 7){
          that.data.occount++;
          that.setData({ occount: that.data.occount })
        }
        
        
        if (clock[i].type == 1 || clock[i].type == 2 || clock[i].type == 3 || clock[i].type == 4 || clock[i].type == 5 || clock[i].type == 6 || clock[i].type == 7 || clock[i].type == 9 || clock[i].type == 11 || clock[i].type == 12 || clock[i].type == 13||clock[i].type==14) { //每日任务打卡时间
         
         for(var a=0;a<clockList.length;a++){
           /////这里写      type不唯一的时候需要 写判断   ，如果type唯一就不需要判断
               if(clockList[a].times==clock[i].times){
                        var swpercentage = 0;
                        //表示上午打卡
                        clockList.morningcount = clockList[a].datalist.length;//表示每个数组里面datalist长度，（例如上午模块的长度）
                       
                        if (that.data.swcount>=0){
                          console.log(222)
                          for (var j = 0; j < clockList[a].datalist.length; j++) {
                            if (clockList[a].datalist[j].type == clock[i].type) {
                              var date = clock[i].createtime.split(' ')[0],
                                time = clock[i].createtime.split(' ')[1];
                              var dates = date.split('-');
                              var times = time.split(':');

                              clockList[a].datalist[j].state = 1;
                              clockList[a].datalist[j].time = dates[1] + '月' + dates[2] + '日 ' + times[0] + ':' + times[1];
                              clockList[a].datalist[j].id = clock[i].id;

                              data['clockList'] = clockList;
                            }

                          }

                        }
                 
                  that.setData({
                    clockList: clockList
                  })
             }
         }
        
        }
        
      }

      //百分比计算
      if (clockList[0].times==1){
        swpercentage = ((that.data.mocount / clockList[0].datalist.length ) * 100).toFixed(0);
        that.setData({
            morningcount: swpercentage
                    })
        clockList[0].timesall = that.data.morningcount
      }
      if(clockList[1].times == 2){
        that.data.swpercentages = ((that.data.swcount / clockList[1].datalist.length) * 100).toFixed(0);
        that.setData({
          swpercentages: that.data.swpercentages
        })
        clockList[1].timesall = that.data.swpercentages
      }
      if (clockList[2].times == 3) {
        that.data.wcpercentage = ((that.data.wccount / clockList[2].datalist.length) * 100).toFixed(0);
        that.setData({
          wcpercentage: that.data.wcpercentage
        })
        clockList[2].timesall = that.data.wcpercentage
      }
      if (clockList[3].times == 4) {
        that.data.xccountage = ((that.data.xccount / clockList[3].datalist.length) * 100).toFixed(0);
        that.setData({
          xccountage: that.data.xccountage
        })
        clockList[3].timesall = that.data.xccountage
      }
      if (clockList[4].times == 5) {
        that.data.accountage = ((that.data.account / clockList[4].datalist.length) * 100).toFixed(0);
        that.setData({
          accountage: that.data.accountage
        })
        clockList[4].timesall = that.data.accountage
      }
      if (clockList[5].times == 6) {
        that.data.bccountage = ((that.data.bccount / clockList[5].datalist.length) * 100).toFixed(0);
        that.setData({
          bccountage: that.data.bccountage
        })
        clockList[5].timesall = that.data.bccountage
      }
      if (clockList[6].times == 7) {
        that.data.occountage = ((that.data.occount / clockList[6].datalist.length) * 100).toFixed(0);
        that.setData({
          occountage: that.data.occountage
        })
        clockList[6].timesall = that.data.occountage
      }
      
    };
    that.setData(data);


  }, pullDown)
}
//检测是否有周任务需要做
function getWeekData(that, patientid) {
  app.https.get(that, '/aiding-web/api/camp/week/' + patientid, {}, function (res) {
    that.setData({
      'weekClock': res
    })
  })
}